package com.example.mytestdemo.view.view

import android.animation.LayoutTransition
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.SparseArray
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.core.util.containsKey
import androidx.core.util.forEach

import com.example.mytestdemo.R
import java.util.concurrent.atomic.AtomicInteger


/**
 * @author tgw
 * @date 2021/7/8
 * @describe 仿h5 样式 效果 的顶部提示弹窗
 */
class CustomTopHintDialog(private val mContext: Context) : Dialog(
    mContext, R.style.TopHintDialog
) {
    private val widthScale = 0.2
    private val heightScale = 0.7


    companion object {
        private const val TAG = "CustomTopHintDialog"
        private const val TIME_OUT = 2 * 1000
    }

    private val mNumber = AtomicInteger(0)
    private var mKey = -1
    private val mTimeOutViewArray: SparseArray<View> = SparseArray<View>(10)
    private val mDismissViewHandler = DialogHandler(this)

    private var view: ViewGroup? = null
    private var rootView: LinearLayout? = null

    fun setChildView(view: ViewGroup): CustomTopHintDialog {
        this.view = view
        return this
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.base_top_dialog_layout)
        // 实例化新的窗口
        val w = window
        //防止状态栏遮挡内容
        w?.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        w?.setLayout(
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT
        )
        val lp = w!!.attributes
        val d = mContext.resources.displayMetrics //获取屏幕的宽和高用
//        lp.width = (d.widthPixels * widthScale).toInt()
        lp.height = (d.heightPixels * heightScale).toInt()
        w.setGravity(Gravity.TOP)
        w.attributes = lp
        //空白处是否可点击消失
        setCanceledOnTouchOutside(true)
//        setCancelable(true)
        //初始化界面控件
        initView()
        //动画效果
        initAnimator()
        setOnDismissListener {
            rootView?.removeAllViews()
            onDestroy()
        }
    }


    override fun show() {
        super.show()
        showAutoDismissTipDialog()
    }

    fun showAutoDismissTipDialog() {
        rootView?.let {
            val childView = view
            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
            )
            lp.gravity = Gravity.CENTER
            childView?.layoutParams = lp
            it.addView(childView)
            mKey = mNumber.getAndIncrement()
            mTimeOutViewArray.put(mKey, childView)
            mDismissViewHandler.sendMessageDelayed(
                mDismissViewHandler.obtainMessage(
                    mKey
                ), TIME_OUT.toLong()
            )
        }
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun initAnimator() {
        val transition = LayoutTransition()
        val animIn = ObjectAnimator.ofFloat(null, "alpha", 0f, 1f)
        val animOut = ObjectAnimator.ofFloat(null, "alpha", 1f, 0f)
        transition.setAnimator(LayoutTransition.APPEARING, animIn)
        transition.setAnimator(LayoutTransition.DISAPPEARING, animOut)
        transition.setDuration(LayoutTransition.APPEARING, 1000)
        transition.setDuration(LayoutTransition.DISAPPEARING, 1000)
        rootView?.layoutTransition = transition
    }

    /**
     * 初始化界面控件
     */
    private fun initView() {
        rootView = findViewById(R.id.root_view)
    }


    private fun dismissDialog(key: Int) {
        val childView: View? = mTimeOutViewArray[key]
        if (childView != null) {
            rootView?.removeView(childView)
        }
        if (mTimeOutViewArray.containsKey(key)) {
            mTimeOutViewArray.remove(key)
        }
        if (rootView != null && rootView!!.childCount <= 0) {
            dismiss()
        }
    }

    /**
     * 移除已存在的消息
     */
    fun onDestroy() {
        mTimeOutViewArray.forEach { key, value ->
            mDismissViewHandler.removeMessages(key)
        }
    }

    private class DialogHandler(val dialog: CustomTopHintDialog) : Handler() {

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            dialog.dismissDialog(msg.what)
        }
    }
}